﻿using FullCoreDBModels;
using FullCoreWebApi.Respository;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace FullCoreControllers
{
    /// <summary>
    /// 患者信息
    /// </summary>

    public class PatientInfoController : APIControllerRoot
    {

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="env"></param>
        /// <param name="_PatientInfoRespository"></param>
        public PatientInfoController(IWebHostEnvironment env, PatientInfoRepository _PatientInfoRespository)
        {
            patientInfoRespository = _PatientInfoRespository;
            webHostEnvironment = env;
        }

        PatientInfoRepository patientInfoRespository;

        private readonly IWebHostEnvironment webHostEnvironment;
        /// <summary>
        /// 获取患者列表
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [HttpGet]
        public List<PatientInfo> GetPatientInfoList(string date)
        {
            return patientInfoRespository.GetPatientInfoList();
        }


        /// <summary>
        /// 通过id获取病人信息
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [HttpGet]

        public PatientInfo GetPatientInfo(string parms)
        {
            return patientInfoRespository.GetPatientInfo(parms);
        }
        /// <summary>
        /// 添加病人信息
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        [HttpPost]

        public CommonResult AddPatient([FromBody] PatientInfo parms)
        {
            return new CommonResult();
        }

        /// <summary>
        /// 本地上传图片信息至服务器处理
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<CommonResult>  SaveImg([FromForm] List<IFormFile> files)
        {
            string imgurl = "";
            int count= Request.Form.Files.Count;
            if (count > 0)
            {
                //foreach (var key in files)
                //{
                //    //这里只测试上传第一张图片file[0]
                //    var file0 = key;
                //    //转换成byte,读取图片MIME类型
                //    Stream stream;
                //    long size = key.Length / 1024; //文件大小KB
                //    if (size > 1024)
                //    {
                //        return new CommonResult() { ReturnData = "上传图片格式有误！", Result = false };
                //    }
                //    byte[] fileByte = new byte[2];//contentLength，这里我们只读取文件长度的前两位用于判断就好了，这样速度比较快，剩下的也用不到。
                //    stream = file0.OpenReadStream();
                //    stream.Read(fileByte, 0, 2);//contentLength，还是取前两位
                //    stream.Close();
                //    //获取图片宽和高
                //    //System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
                //    //int width = image.Width;
                //    //int height = image.Height;
                //    string fileFlag = "";
                //    if (fileByte != null && fileByte.Length > 0)//图片数据是否为空
                //    {
                //        fileFlag = fileByte[0].ToString() + fileByte[1].ToString();
                //    }
                //    string[] fileTypeStr = { "255216", "7173", "6677", "13780" };//对应的图片格式jpg,gif,bmp,png
                //    if (true)//fileTypeStr.Contains(fileFlag)
                //    {
                //        //文件名称     我用的时间+名称处理  一般会增加一个随机数
                //        string fileName = DateTime.Now.Millisecond + file0.FileName;
                //        //校验文件夹是否存在  不存在进行创建
                //        string fullpath = Path.Combine(webHostEnvironment.ContentRootPath, "uploads", DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString());
                //        if (!Directory.Exists(fullpath))
                //        {
                //            Directory.CreateDirectory(fullpath);
                //        }
                //        //文件保存信息
                //        using (var streamwite = new FileStream(fullpath + fileName, FileMode.Create))
                //        {
                //            file0.CopyTo(streamwite);
                //            stream.Flush();
                //        }

                //        //最后输出存储的图片路径信息
                //        imgurl = fullpath + fileName;
                //    }
                //    else
                //    {
                //        return new CommonResult() { ReturnData = "上传图片格式有误！", Result = false };
                //    }

                //}
                foreach (var formFile in Request.Form.Files)
                {
                    if (formFile != null && formFile.Length > 0)
                    {
                        var filePath = Path.GetTempFileName();

                        var filePath1 = Path.Combine("", Path.GetRandomFileName());

                        #region  图片文件的条件判断

                        //没有后缀扩展名的文件名
                        var currentPictureWithoutExtension = Path.GetFileNameWithoutExtension(formFile.FileName);

                        //文件后缀
                        var fileExtension = Path.GetExtension(formFile.FileName).ToUpper();

                        //判断后缀是否是图片
                        const string fileFilt = ".gif|.jpg|.jpeg|.png";
                        if (fileExtension == null)
                            return new CommonResult() { ReturnData = "上传的文件没有后缀", Result = false };;

                        if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                            
                        return new CommonResult() { ReturnData = "请上传jpg、png、gif格式的图片", Result = false }; ;
                        //判断文件大小    
                        long length = formFile.Length;
                        //if (length > 1024 * 1024 * 2) //2M
                        //    return new JsonResult(new { code = "-1", msg = "上传的文件不能大于2M" });

                        #endregion
                        
                        string fileName = DateTime.Now.Millisecond + formFile.FileName;
                        //校验文件夹是否存在  不存在进行创建
                        string fullpath = Path.Combine(webHostEnvironment.ContentRootPath, "uploads");
                        if (!Directory.Exists(fullpath))
                        {
                            Directory.CreateDirectory(fullpath);
                        }
                        #region 上传图片
                        string fullname = Path.Combine(fullpath,fileName);
                        using (var stream = System.IO.File.Create(fullname))
                        {
                            await formFile.CopyToAsync(stream);
                        }
                        imgurl = fullpath + fileName;
                        #endregion
                    }
                }
     
            }
          
            return new CommonResult() { ReturnData = imgurl, Result = true };
        }
    }
}
